package com.example.securitydemo.security.userdetails;

import com.example.securitydemo.domain.User;
import com.example.securitydemo.repository.UserRepo;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
@RequiredArgsConstructor
public class UserDetailsPasswordServiceImpl implements UserDetailsPasswordService {

    private final UserRepo userRepo;

    // 无缝密码升级，在用户登录时就更新密码了
    @Override
    public UserDetails updatePassword(UserDetails userDetails, String newPassword) {
        return userRepo.findOptionalByUsername(userDetails.getUsername())
                .map(userFromDb -> userRepo.save(userFromDb.withPassword(newPassword)))
                .orElseThrow();
    }
}
